﻿//  Symplectic Spark
//  Copyright 2010 Symplectic Ltd
//  Created by Martyn Whitwell (martyn@symplectic.co.uk)

//  This file is part of Spark.

//  Spark is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  Spark is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with Spark.  If not, see <http://www.gnu.org/licenses/>.

// $URL: https://symplectic-spark.googlecode.com/svn/trunk/website/App_Code/ValidateConfiguration.cs $
// $LastChangedDate: 2010-03-30 14:27:49 +0100 (Tue, 30 Mar 2010) $
// $LastChangedRevision: 24 $
// $LastChangedBy: martyn@symplectic.co.uk $

using System;
using System.Threading;
using System.IO;
using System.Web.Hosting;
using System.Configuration;
using System.Xml.Linq;
using System.Xml.XPath;

/// <summary>
/// Summary description for ValidateConfiguration
/// </summary>

namespace Symplectic.Spark
{
    public static class ValidateConfiguration
    {
        public static bool Check()
        {
            try
            {
                string privateFolderAbsolute = checkRelativeDirectory(checkWebConfigValue("private-folder"));
                string bufferFolderAbsolute = createRelativeDirectory(checkWebConfigValue("buffer-folder"));
                string publicPathVirtual = checkRelativeDirectory(checkWebConfigValue("public-path"));

                checkRelativeDirectory(Global.XslPathAbsolute);
                checkRelativeDirectory(Global.TemplatePathAbsolute);

                XElement xComponents = XElement.Load(checkFileExists(Global.ComponentsPathAbsolute));
                string fileElementTypes = checkFileExists(Global.ElementTypesPathAbsolute);
                XElement xElementTypes = XElement.Load(fileElementTypes);

                try { int.Parse(Global.PerPage); }
                catch { throw new ArgumentOutOfRangeException("per-page", Global.PerPage, "Unable to parse web.config app setting - must be an integer"); }
                

                //validate that all the HTML templates are in place
                foreach (XElement element in xElementTypes.XPathSelectElements("//element-type/index | //element-type/item"))
                    checkFileExists(Path.Combine(Global.TemplatePathAbsolute, element.Attribute("template").Value));

                //validate that all the XSL stylesheets are in place
                foreach (XElement element in xComponents.XPathSelectElements("//*[@xsl]"))
                    checkFileExists(Path.Combine(Global.XslPathAbsolute, element.Attribute("xsl").Value));

                //validate that elementTypes contains a definition for error and root                
                checkElementExists(xElementTypes, "//element-type[@name='error']/index[@template]", fileElementTypes);
                checkElementExists(xElementTypes, "//element-type[@name='root']/index[@template]", fileElementTypes);
                
                return true; //validated OK.
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Spark Configuration does not validate - please check settings, paths and files", ex);
            }
        }

        private static string checkWebConfigValue(string configurationName)
        {
            string value = ConfigurationSettings.AppSettings[configurationName];
            if (value == null)
                throw new ArgumentNullException(configurationName, "Not defined in Web.Config");
            return value;
        }

        private static string checkRelativeDirectory(string relativeDirectory)
        {
            string absoluteDirectory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, relativeDirectory);
            if (!Directory.Exists(absoluteDirectory))
                throw new DirectoryNotFoundException("Directory not found: " + absoluteDirectory);
            return absoluteDirectory;
        }

        private static string createRelativeDirectory(string relativeDirectory)
        {
            string absoluteDirectory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, relativeDirectory);
            if (!Directory.Exists(absoluteDirectory))
            {
                Directory.CreateDirectory(absoluteDirectory);
                Thread.Sleep(500); //sleep a moment to ensure folder gets created
            }
            if (!Directory.Exists(absoluteDirectory))
                throw new DirectoryNotFoundException("Directory could not be created: " + absoluteDirectory);
            return absoluteDirectory;
        }

        private static string checkFileExists(string file)
        {
            if (!File.Exists(file))
                throw new FileNotFoundException("File not found: " + file, file);
            return file;
        }

        private static void checkElementExists(XElement document, string xpath, string filename)
        {
            if (document.XPathSelectElement(xpath) == null)
                throw new NotImplementedException("No elements matched: " + xpath + " in " + filename);
        }
    }
}